import React, { useState, useMemo } from 'react';
import { useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import {
  AppBar,
  Toolbar,
  Typography,
  Button,
  Drawer,
  Box,
  CssBaseline,
  IconButton
} from '@mui/material';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import MenuIcon from '@mui/icons-material/Menu';

import AdminMenuList from '../components/admin/AdminMenuList';
import UserInfoDialog from '../components/UserInfoDialog';

const drawerWidth = 120; // Adjust the width as per your requirement

const AdminLayout = ({ children }) => {
  const [openDialog, setOpenDialog] = useState(false);
  const [menuOpen, setMenuOpen] = useState(true);
  const accessToken = useSelector((state) => state.auth.isAuthenticated);

  const userInfo = {
    fullName: '测试设计',
    phoneNumber: '123456789',
    departmentName: '综合'
  };

  const toggleDialog = () => {
    setOpenDialog(!openDialog);
  };

  const toggleMenu = () => {
    setMenuOpen(!menuOpen);
  };

  const MemoizedAdminMenuList = useMemo(() => (
    <AdminMenuList accessToken={accessToken} />
  ), [accessToken]);

  return (
    <Box sx={{ display: 'flex', height: '100vh' }}>
      <CssBaseline />
      <AppBar position="fixed" sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }}>
        <Toolbar>
          <IconButton
            color="inherit"
            edge="start"
            onClick={toggleMenu}
            sx={{ marginRight: 2 }}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" sx={{ flexGrow: 1 }}>
            代码生成-管理后台
          </Typography>
          <Button color="inherit" onClick={toggleDialog}>
            <AccountCircleIcon />
          </Button>
        </Toolbar>
      </AppBar>
      {menuOpen && (
        <Drawer
          variant="permanent"
          sx={{
            width: drawerWidth,
            flexShrink: 0,
            '& .MuiDrawer-paper': { width: drawerWidth, boxSizing: 'border-box' }
          }}
        >
          <Toolbar />
          {MemoizedAdminMenuList}
        </Drawer>
      )}
      <Box
        component="main"
        sx={{
          flexGrow: 1,
          p: 0,
          marginLeft: menuOpen ? `auto` : '0px',
          marginTop: '64px', // Adjusting for the AppBar height
          width: menuOpen ? `calc(100% - ${drawerWidth}px)` : '100%', // Ensures full width usage
          transition: 'margin-left 0.3s, width 0.3s'
        }}
      >
        {children}
      </Box>
      <UserInfoDialog open={openDialog} onClose={toggleDialog} userInfo={userInfo} />
    </Box>
  );
};

AdminLayout.propTypes = {
  children: PropTypes.node.isRequired,
};

export default AdminLayout;
